import _ from "lodash";
import API from "@/api";

export const table = {
  data: () => ({
    isLoading: true,
    searchForm: {},
    tableData: [],
    tableTotal: 0,
    selectList: [], // 表格选中行
    delName: "",
    isKey: false,
    pagination: {
      page: 1, // 当前页码
      per_page: 20, // 每页条数
    },
  }),
  watch: {
    pagination: {
      immediate: true,
      deep: true,
      handler: _.debounce(function () {
        this.fetchData();
      }, 300),
    },
  },
  methods: {
    // 更新表格数据
    fetchData(page) {
      if (!isNaN(page)) this.pagination.page = page;
      // $符开头键名 》自定义不做提交
      const keys = Object.keys(this.searchForm).filter(
        (k) => !k.startsWith("$")
      );
      const options = _.pick(this.searchForm, keys);
      const params = Object.assign({}, options, this.pagination);
      let listKey = _.get(this.searchForm, "$action.0", "");
      if (listKey) {
        API[listKey](params)
          .then(({ data }) => {
            this.isKey = !this.isKey;
            this.tableData = data.items;
            this.tableTotal = data.total;
          })
          .finally(() => (this.isLoading = false));
      } else {
        this.isLoading = false;
      }
    },

    // 搜索
    submitSearch() {
      this.$refs["searchForm"]
        .validate()
        .then(() => {
          this.fetchData(1);
        })
        .catch();
    },

    // 重置
    resetSearch() {
      this.$refs["searchForm"].resetFields();
      this.$nextTick(() => this.fetchData());
    },

    // 删除单个
    async delRowById({ id, name, username }, NAME) {
      this.delName = NAME || name || username;
      await this.$nextTick();
      this.$confirm(
        `是否删除 <span style="color:#337dde">${this.delName}</span> 这条数据？`,
        "提示",
        {
          type: "warning",
          dangerouslyUseHTMLString: true,
          roundButton: true, // 圆角
        }
      )
        .then(() => {
          let delKey = _.get(this.searchForm, "$action.1", "");
          let delAllKey = _.get(this.searchForm, "$action.2", "");
          if (delKey) {
            return API[delKey](id);
          } else if (delAllKey) {
            return API[delAllKey]({ id_list: [id] });
          } else {
            // return Promise.reject()
          }
        })
        .then(() => {
          // this.$message.success("删除成功！");
          this.$notify({
            title: "成功",
            message: `${this.delName} 已删除`,
            type: "success",
          });
          this.fetchData();
        })
        .catch(({ code }) => {
          if (code === 11100) {
            this.$message({
              iconClass: " ",
              // duration: 0,
              customClass: "errmsg_box",
              // dangerouslyUseHTMLString: true,
              message: "删除失败",
              // message: this.$refs.del_err.outerHTML,
            });
          }
        });
    },

    // 批量删除
    delBatchRow(key) {
      if (typeof key !== "string" || !key) {
        key = "id_list";
      }
      let params = {
        [key]: this.selectList,
      };
      this.$confirm("确认删除所有选中项吗？", this.$refs.del_title.innerText, {
        type: "warning",
      }).then(() => {
        let delKey = _.get(this.searchForm, "$action.2", "");
        if (delKey)
          API[delKey](params)
            .then(() => {
              // this.$message.success('批量删除成功！！')
              this.$notify({
                title: "成功",
                message: `批量删除掉${this.selectList.length}条数据`,
                type: "success",
              });
              this.fetchData(1);
            })
            .catch((err) => {
              console.log("批量删除异常", err);
            });
        // 仅供测试
        else
          this.$notify({
            title: "成功",
            message: `批量删除掉${this.selectList.length}条数据`,
            type: "success",
          });
      });
    },
  },
};

export const addOrEdit = {
  data: () => ({
    loading: {
      update: false, // 新增/编辑中。。。
    },
    showAddOrEdit: false, // 新增/编辑弹窗
  }),

  methods: {
    // 提交 新增/编辑
    async submitRowData(formName, callBack = false) {
      let source = this[formName];
      // 多图上传
      if (_.has(source, "$fileListKey")) {
        let PArr = source.$fileList
          .filter((v) => v.raw)
          .map(({ raw }) => {
            let formData = new FormData();
            formData.append("img", raw);
            return API.pushMultipleImg(formData).then(({ data }) => data.id);
          });
        let idList = await Promise.all(PArr);
        source[source.$fileListKey] = _.concat(
          source[source.$fileListKey],
          ...idList
        );
      }
      this.$refs[formName]
        .validate()
        .then(() => {
          const keys = Object.keys(source).filter((k) => !k.startsWith("$"));
          const options = _.pick(source, keys);
          for (const [key, val] of Object.entries(options)) {
            if (val === null) delete options[key];
          }
          this.loading.update = true;
          // 单图上传
          if (_.has(source, "$image_uri")) {
            let formData = new FormData();
            for (const entries of Object.entries(options)) {
              formData.append(...entries);
            }
            return source.$id
              ? API[source.$action[1]](source.$id, formData)
              : API[source.$action[0]](formData);
          }
          // 获取权限菜单
          if (_.has(options, "permission")) {
            options.permission = this.$refs.tree.getCheckedKeys(true);
          }
          return source.$id
            ? API[source.$action[1]](source.$id, options)
            : API[source.$action[0]](options);
          // return new Promise((resolve) => setTimeout(() => resolve(), 1000));
        })
        .then(() => {
          if (source.$show) this[source.$show] = false;
          else this.showAddOrEdit = false;
          source.$image_uri = "";
          if (source.$id) {
            this.$message.success("编辑成功！");
          } else {
            this.$message.success("新增成功！");
          }
          if (callBack) callBack();
          else this.fetchData(1);
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          this.loading.update = false;
        });
    },

    // 打开编辑弹窗
    openEditRow(row, formName, callBack) {
      let source = this[formName];
      if (source.$show) this[source.$show] = true;
      else this.showAddOrEdit = true;
      // 弹窗内容为懒加载，第一次打开需在渲染完后再对表单进行赋值
      this.$nextTick(() => {
        const target = _.pick(row, Object.keys(source));
        Object.assign(source, target);
        callBack && callBack({ source, row });
        if (source.$imgKey) {
          source.$image_uri = row[source.$imgKey];
        }
        source.$id = row.id;
      });
    },
  },
};

export const status = {
  data: () => ({
    status: [
      {
        value: 1,
        label: "待受理",
      },
      {
        value: 2,
        label: "已受理",
      },
    ],
    statusClass: {
      1: "blue",
      2: "green",
    },
  }),
  computed: {
    statusObj() {
      return this.status.reduce(
        (acc, cur) => ((acc[cur.value] = cur.label), acc),
        {}
      );
    },
  },
};

export const auditStatus = {
  data: () => ({
    auditStatus: [
      {
        value: 1,
        label: "待审核",
      },
      {
        value: 2,
        label: "通过",
      },
      {
        value: 3,
        label: "未通过",
      },
    ],
    auditClass: {
      1: "blue",
      2: "green",
      3: "red",
    },
  }),
  computed: {
    auditObj() {
      return this.auditStatus.reduce(
        (acc, cur) => ((acc[cur.value] = cur.label), acc),
        {}
      );
    },
  },
};
